package org.itboys.advertisement.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.itboys.advertisement.cache.AdvertisementLoader;
import org.itboys.advertisement.entity.Adzone;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseService;
import org.itboys.mongodb.utils.query.AceUtils;
import org.springframework.stereotype.Service;

/**
 * 广告位
 * @author weisky
 *
 */
@Service
public class AdzoneService extends BaseService<Adzone, Long> {

	private static final long serialVersionUID = 7595909451637453796L;
	
	@Resource(name="advertisementDs")
    private MongoDataSource advertisementDs;
	
    @Resource(name="advertisementLoader")
    private AdvertisementLoader advertisementLoader;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return advertisementDs;
    }

    @Override
    protected Class<Adzone> getEntityClass() {
        return Adzone.class;
    }
    
    /**
	 * 根据名称模糊查询列表
	 * @param shopName
	 * @return
	 */
	public List<Adzone> getAdzoneByName(String name) {
		return advertisementDs.createQuery(getEntityClass())
				.filter("name", AceUtils.getPattern(name))
				.filter("isDeleted", 0).asList();
	}
    
    /**
     * 新增或者修改
     * @param adzone
     * @return 0:系统错误  1:操作成功  -1:key值不能为空  -2:key值已存在
     */
    public int insert(Adzone adzone){
    	try{
    		
    		if(StringUtils.isBlank(adzone.getKey())){
    			return -1;//key值不能为空
    		}
    		
    		if(adzone.getId() != 0){
    			super.update(adzone);
    		}else{
    			if(super.exists("key", adzone.getKey())){
        			return -2;//key值已存在
        		}
    			super.save(adzone);
    		}
    		advertisementLoader.clearCache(adzone.getKey());//清除缓存中的值
    		return 1;//操作成功
    	}catch(Exception e){
    		logger.error("AdzoneService.insert error, Adzone="+ToStringBuilder.reflectionToString(adzone), e);
    		return 0;//系统错误
    	}
    }
    
    /**
     * 删除
     * @param id
     * @return
     */
    public boolean dele(Long id){
    	try{
    		super.delete(id);
    		return true;
    	}catch(Exception e){
    		logger.error("AdzoneService.dele error, id="+id, e);
    		return false;//系统错误
    	}
    }
    
    
}
